package cn.itcast.controller;


import cn.itcast.constant.MessageConstant;
import cn.itcast.entity.Result;
import cn.itcast.service.ReportBusinessService;
import cn.itcast.utils.DateUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/report")
@Slf4j
public class ReportBusinessController {


    @Reference(version = "1.0.0")
    private ReportBusinessService reportBusinessService;

    /**
     * 运营数据统计
     * @return
     */
    @GetMapping("/business")
    public Result reportBusiness(){
        //获取今天的日期
        Calendar calendar = Calendar.getInstance();
        Date today = calendar.getTime();
        //根据当前日期获取所在周的开始日期
        Date startWeekDay = DateUtils.getFirstDayOfWeek(today);
        //根据当前日期获取所在周结束日期
        Date endWeekDay = DateUtils.getLastDayOfWeek(today);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        //今日日期
        String todayDate = sdf.format(today);
        log.info("今日日期:{}",todayDate);
        //本周开始时间
        String startWeek = sdf.format(startWeekDay);
        log.info("本周开始时间:{}",startWeek);
        //本周结束时间
        String endWeek = sdf.format(endWeekDay);
        log.info("本周结束时间:{}",endWeek);
        SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM");
        //本月时间
        String month = sdf1.format(today);
        log.info("本月时间:{}",month);

        Map<String, Object> result = this.reportBusinessService.reportBusiness(todayDate, startWeek, endWeek, month);
        return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS,result);
    }


    /**
     * 导出excel表
     */
    @RequestMapping("/export/business")
    public Result getExcel(HttpServletRequest request,
                           HttpServletResponse response){
        try {
            //取出返回结果数据，准备将报表数据写入到Excel文件中
            Result result1= this.reportBusiness();
            Map<String,Object> result = (Map<String, Object>) result1.getData();


            //今天日期
            String reportDate = (String) result.get("reportDate");
            //新增会员数
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            //总会员数
            Integer totalMember = (Integer) result.get("totalMember");
            //本周新增会员数
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            //本月新增会员数
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            //今日预约数
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            //本周预约数
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            //本月预约数
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            //今日到诊数
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            //本周到诊数
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            //本月到诊数
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            //热门套餐集合
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

            //SpringBoot读取resources目录下的文件 网上说打jar包后也可以
            Resource resource = new ClassPathResource("static/template/report_template.xlsx");
            System.out.println(resource);
            String path = resource.getFile().getPath();
            System.out.println(path);

            //读取模板文件创建Excel表格对象
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(path)));
            XSSFSheet sheet = workbook.getSheetAt(0);


            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);  //日期

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);   //新增会员数（本日）
            row.getCell(7).setCellValue(totalMember);      //总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);   //本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);  //本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);    //今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);    //今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);   //本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);   //本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);   //本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);   //本月到诊数

            int rowNum = 12;
            for(Map map : hotSetmeal){           //热门套餐
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row = sheet.getRow(rowNum ++);
                row.getCell(4).setCellValue(name);//套餐名称
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());//占比
            }

            //通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            workbook.write(out);

            out.flush();
            out.close();
            workbook.close();

            return null;
        } catch (Exception e) {
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL,null);
        }
    }
}
